#include "UserInterface.h"
#include <GL/gl.h>
#include <SDL/SDL.h>
#include "InvisibleCube.h"

#include <iostream>
using namespace std;

UserInterface::UserInterface(Sound * aSound, Cursor * aCursor, Cube * aCube)
{
	pile = new CubePile(aCube, aSound, -0.5, -1, NULL);
	cursor = aCursor;
	grabMode = true;
}

UserInterface::~UserInterface()
{
}

void UserInterface::render()
{
	glPushMatrix();
		glBegin(GL_QUADS);
		
			//TOP
			glColor4f(1.0f,1.0f,1.0f, 1.0f);			// Full Brightness, 50% Alpha ( NEW )
		
			//front face
			glVertex3f(-1.1, 1, -2);
			glVertex3f( -0.5, 1, -2);
			glVertex3f( -0.5,-1, -2);
			glVertex3f(-1.1,-1, -2);
			
		glEnd();
		
		float scale = 0.04;
		
		glPushMatrix();
			glTranslatef(-0.4, -0.4, -1);
			glScalef(scale, scale, scale);
			glRotatef(10, 1, 0, 0);
			pile->render();
		glPopMatrix();
		
		/*
		 * for the moment I'm keeping patterns on speach bubbles, but in case I want to move it back to the UI...
		if (pattern != NULL)
		{
			glPushMatrix();
				glTranslatef(-0.5, 0.4, -1);
				glScalef(scale, scale, scale);
				pattern->render();
			glPopMatrix();
		}
		*/
		
	
	glPopMatrix();
	
}


void UserInterface::animate(float timeD)
{
	pile->animate(timeD);
}

void UserInterface::handleEvent(bool keys[321])
{
	grabMode = keys[SDLK_LSHIFT] || keys[SDLK_RSHIFT] ;
	 
	if(keys[SDLK_SPACE])
	{
		if(grabMode)
		{
			grab();
		}
		else
		{
			drop();
		}
	}
}

void UserInterface::grab()
{
	CubePile * target = cursor->getCurrentPile();
	if(target->getFeature() != NULL)
	{
		target->getFeature()->handleMouseClickEvent();
	}
	else if(target->size() > 1 && !target->isLocked())
	{
		pile->dropCube(target->popCube());
	}
}

void UserInterface::drop()
{
	CubePile * target = cursor->getCurrentPile();
	if( (pile->size() > 1) && target->canDropCube())
	{
		Cube * dropCube  = pile->popCube();
		dropCube->yPos = CUBE_Y_DROP;
		target->dropCube(dropCube);
	}
}

void UserInterface::handleEvent(SDL_Event * event)
{
	if(event->type == SDL_MOUSEBUTTONDOWN)
	{
		if( event->button.button == SDL_BUTTON_LEFT )
		{
			grab();
		}
		else if(event->button.button == SDL_BUTTON_RIGHT )
		{
			drop();
		}
	}
}
